package com.s3u4.demo.zookeeper.base;

import com.s3u4.demo.zookeeper.ZkConfig;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Captain on 01/08/2017.
 */
public class ConnectionWatcher implements Watcher {

    protected ZooKeeper zooKeeper;

    protected CountDownLatch connectSinal = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("process with watcher status :" + watchedEvent.getState() );
        if ( watchedEvent.getState() == Event.KeeperState.SyncConnected ){
            connectSinal.countDown();
        }
    }

    protected void connect(String hosts) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(hosts, ZkConfig.SESSION_TIMECOUNT,this);
        connectSinal.await();
    }

    protected void close() throws InterruptedException {
        zooKeeper.close();
    }

}
